import dayjs from "dayjs";
// import { nanoid } from "nanoid";
import SparkMD5 from "spark-md5";

export const FileType = {
	// 文档
	application: {
		format: ["pdf", "ppt", "pptx", "doc", "docx", "xls", "xlsx"],
		rootPath: "/document/",
		size: 1024 * 1024 * 100,
		sizeName: "100M"
	},
	// 音频
	audio: {
		format: ["mp3", "wav"],
		rootPath: "/audio/",
		size: 1024 * 1024 * 100,
		sizeName: "100M"
	},
	// 图片
	image: {
		format: ["jpg", "jpeg", "png", "webp", "gif"],
		rootPath: "/image/",
		size: 1024 * 1024 * 10,
		sizeName: "10M"
	},
	// 视频
	video: {
		format: ["mp4"],
		rootPath: "/video/",
		size: 1024 * 1024 * 1024 * 1,
		sizeName: "1G"
	}
};

/**
 * @description 获取文件 MD5 值
 * @param {File} file 文件对象
 * @return {String} 文件 MD5 值
 **/
export const getFileMD5 = async file => {
	const chunkSize = 2097152;
	const chunks = Math.ceil(file.size / chunkSize);
	let currentChunk = 0;
	const spark = new SparkMD5.ArrayBuffer();
	const loadNextChunk = (fileReader, file, start, end) => {
		return new Promise((resolve, reject) => {
			fileReader.onload = e => {
				try {
					spark.append(e.target.result);
					resolve();
				} catch (error) {
					reject(error);
				}
			};
			fileReader.onerror = error => {
				reject(error);
			};
			fileReader.onabort = () => {
				reject(new Error("文件读取被中止"));
			};
			fileReader.readAsArrayBuffer(file.slice(start, end));
		});
	};
	try {
		const fileReader = new window.FileReader();
		while (currentChunk < chunks) {
			const start = currentChunk * chunkSize;
			const end = Math.min(start + chunkSize, file.size);
			await loadNextChunk(fileReader, file, start, end);
			currentChunk++;
		}
		const md5 = spark.end();
		spark.destroy();
		return md5;
	} catch (error) {
		throw new Error(error);
	}
};

/**
 * @description 将 file 地址链接转换为 ArrayBuffer 或 Blob
 * @param {string} url
 * @param {Boolean} isBlob
 * @return {Promise<ArrayBuffer>}
 **/
export const getArrayBuffer = async (url, isBlob = false) => {
	const res = await fetch(url);
	if (isBlob) {
		return await res.blob();
	} else {
		const buffer = await res.arrayBuffer();
		return new Uint8Array(buffer);
	}
};

/**
 * @description 自定义截取文件上传
 * @param {File} file 文件对象
 * @param {String} fileName 文件名
 * @param {String} rootPath 根路径
 * @param {String} upType 上传类型：参照 FileType
 * @return {Object} 文件信息
 **/
export const getSnapFileInfo = ({ file, fileName, rootPath, upType }) => {
	const fileSize = 0;
	const datePath = dayjs().format("YYYY/MM/DD");
	const upPath = `${rootPath}/${upType}/${datePath}/`;
	const endDotIndex = fileName.lastIndexOf(".");
	const suffixName = fileName.substring(endDotIndex + 1);
	return {
		file,
		fileMd5: "",
		fileName,
		rootPath: upPath,
		size: fileSize,
		suffixName
	};
};
